package com.jbtm.mall;

import com.jbtm.mall.common.ServerResponse;
import com.jbtm.mall.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by ali on 2018/4/2.
 * 全局异常处理异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public static final String DEFAULT_ERROR_VIEW = "error";


    @ExceptionHandler(BizException.class)
    public ServerResponse bizExceptionHandler(HttpServletRequest req, Exception e) throws Exception {

        log.error("==============自定义BizException Start=================");
        log.error(String.format("Url  = %s, Date = %s", req.getRequestURL(), new Date()));
        e.printStackTrace();
        log.error("==============自定义BizException End===================");
        return ServerResponse.errorMessage(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);

        //打印日志到控制台
        log.error("==============Exception Start=================");
        log.error(String.format("Url  = %s, Date = %s", req.getRequestURL(), new Date()));
        e.printStackTrace();
        log.error("==============Exception End===================");
        return mav;
    }

}
